<template>
  <div class="category-foods-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <div class="header-content">
          <div class="breadcrumb">
            <router-link to="/categories" class="breadcrumb-link">美食分类</router-link>
            <span class="breadcrumb-separator">></span>
            <span class="breadcrumb-current">{{ currentCategory.categoryName || '加载中...' }}</span>
          </div>
          <h1>
            <span class="category-emoji">{{ currentCategory.categoryEmoji || '🍽️' }}</span>
            {{ currentCategory.categoryName || '分类菜品' }}
          </h1>
          <p class="category-description">{{ currentCategory.categoryDescription || '探索美味菜品' }}</p>
        </div>
      </div>
    </div>

    <div class="container">
      <!-- 分类筛选器 -->
      <div class="filters-section">
        <div class="category-tabs">
          <el-button 
            :type="selectedCategoryId === null ? 'primary' : ''"
            @click="filterByCategory(null)"
            class="category-tab"
          >
            全部 ({{ totalFoodsCount }})
          </el-button>
          <el-button 
            v-for="category in allCategories" 
            :key="category.categoryId"
            :type="selectedCategoryId === category.categoryId ? 'primary' : ''"
            @click="filterByCategory(category.categoryId)"
            class="category-tab"
          >
            {{ category.categoryEmoji }} {{ category.categoryName }} ({{ category.foodCount || 0 }})
          </el-button>
        </div>

        <!-- 搜索和排序 -->
        <div class="filter-controls">
          <el-input
            v-model="searchQuery"
            placeholder="搜索菜品..."
            prefix-icon="Search"
            style="width: 300px; margin-right: 16px;"
            @input="handleSearch"
            clearable
          />
          <el-select v-model="sortBy" @change="handleSort" placeholder="排序方式" style="width: 160px;">
            <el-option label="综合排序" value="default" />
            <el-option label="价格升序" value="price_asc" />
            <el-option label="价格降序" value="price_desc" />
            <el-option label="评分最高" value="rating_desc" />
            <el-option label="最新上架" value="newest" />
          </el-select>
        </div>
      </div>

      <!-- 菜品网格 -->
      <div class="foods-section" v-loading="loading">
        <div v-if="filteredFoods.length === 0 && !loading" class="empty-state">
          <div class="empty-icon">🍽️</div>
          <h3>暂无菜品</h3>
          <p>{{ searchQuery ? '没有找到相关菜品，试试其他关键词' : '该分类下暂无菜品' }}</p>
        </div>

        <div v-else class="foods-grid">
          <div 
            v-for="food in filteredFoods" 
            :key="food.foodId"
            class="food-card"
            @click="viewFoodDetail(food.foodId)"
          >
            <div class="food-image-container">
              <el-image 
                :src="getImageUrl(food.foodImagePath)" 
                class="food-image"
                fit="cover"
                lazy
              >
                <template #error>
                  <el-image 
                    src="/food.png" 
                    class="food-image"
                    fit="cover"
                  />
                </template>
              </el-image>
              <div class="food-overlay">
                <el-button type="primary" size="small" round>查看详情</el-button>
              </div>
            </div>
            
            <div class="food-info">
              <h3 class="food-name">{{ food.foodName }}</h3>
              <p class="food-description">{{ food.foodDescription || '暂无描述' }}</p>
              
              <div class="food-meta">
                <div class="rating" v-if="food.rating > 0">
                  <el-rate 
                    :model-value="parseFloat(food.rating)" 
                    disabled 
                    show-score 
                    text-color="#ff9800"
                    score-template="{value}"
                    size="small"
                  />
                </div>
                <div class="merchant-info">
                  <router-link :to="`/merchant/${food.merchantId}`" class="merchant-link">
                    {{ food.merchantName }}
                  </router-link>
                </div>
              </div>
              
              <div class="food-footer">
                <div class="price">
                  <span class="currency">¥</span>
                  <span class="amount">{{ food.foodPrice }}</span>
                </div>
                <div class="category-tag">
                  {{ food.categoryName }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[12, 24, 48]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'CategoryFoodsView',
  data() {
    return {
      loading: false,
      currentCategory: {},
      allCategories: [],
      foods: [],
      filteredFoods: [],
      selectedCategoryId: null,
      searchQuery: '',
      sortBy: 'default',
      pagination: {
        page: 1,
        size: 12,
        total: 0
      }
    }
  },
  computed: {
    totalFoodsCount() {
      return this.foods.length
    }
  },
  mounted() {
    this.initPage()
  },
  watch: {
    '$route'(to, from) {
      if (to.params.categoryId !== from.params.categoryId) {
        this.initPage()
      }
    }
  },
  methods: {
    async initPage() {
      const categoryId = this.$route.params.categoryId
      // 如果路径是 /category/all，设置为null显示所有分类
      this.selectedCategoryId = (categoryId && categoryId !== 'all') ? parseInt(categoryId) : null
      
      await Promise.all([
        this.loadCategories(),
        this.loadCurrentCategory(),
        this.loadFoods()
      ])
    },

    async loadCategories() {
      try {
        const response = await fetch('http://localhost:2077/api/categories')
        const data = await response.json()
        
        if (data.success) {
          this.allCategories = data.data || []
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },

    async loadCurrentCategory() {
      if (!this.selectedCategoryId) {
        this.currentCategory = {
          categoryName: '全部分类',
          categoryEmoji: '🍽️',
          categoryDescription: '浏览所有美味菜品'
        }
        return
      }

      try {
        const response = await fetch(`http://localhost:2077/api/categories/${this.selectedCategoryId}`)
        const data = await response.json()
        
        if (data.success) {
          this.currentCategory = data.data
        }
      } catch (error) {
        console.error('加载分类信息失败:', error)
      }
    },

    async loadFoods() {
      this.loading = true
      try {
        let url = 'http://localhost:2077/api/foods'
        const params = new URLSearchParams({
          page: this.pagination.page,
          size: this.pagination.size
        })

        if (this.selectedCategoryId) {
          params.append('categoryId', this.selectedCategoryId)
        }

        if (this.searchQuery) {
          params.append('search', this.searchQuery)
        }

        if (this.sortBy !== 'default') {
          params.append('sort', this.sortBy)
        }

        const response = await fetch(`${url}?${params}`)
        const data = await response.json()
        
        if (data.success) {
          this.foods = data.data.data || []
          this.pagination.total = data.data.total || 0
          this.filteredFoods = [...this.foods]
        } else {
          ElMessage.error(data.message || '加载菜品失败')
        }
      } catch (error) {
        console.error('加载菜品失败:', error)
        ElMessage.error('加载菜品失败')
      } finally {
        this.loading = false
      }
    },

    filterByCategory(categoryId) {
      this.selectedCategoryId = categoryId
      this.pagination.page = 1
      
      // 更新路由
      if (categoryId) {
        this.$router.push(`/category/${categoryId}`)
      } else {
        this.$router.push('/category/all')
      }
      
      this.loadFoods()
    },

    handleSearch() {
      this.pagination.page = 1
      this.loadFoods()
    },

    handleSort() {
      this.pagination.page = 1
      this.loadFoods()
    },

    handlePageChange(page) {
      this.pagination.page = page
      this.loadFoods()
    },

    handlePageSizeChange(size) {
      this.pagination.size = size
      this.pagination.page = 1
      this.loadFoods()
    },

    viewFoodDetail(foodId) {
      this.$router.push(`/food/${foodId}`)
    },

    getImageUrl(imagePath) {
      if (!imagePath) return '/food.png'
      if (imagePath.startsWith('http')) return imagePath
      return imagePath.startsWith('/') ? imagePath : `/${imagePath}`
    }
  }
}
</script>

<style scoped>
.category-foods-view {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
  margin-bottom: 30px;
}

.header-content {
  text-align: center;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  opacity: 0.9;
}

.breadcrumb-link {
  color: white;
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  margin: 0 10px;
}

.breadcrumb-current {
  font-weight: 600;
}

.page-header h1 {
  margin: 0 0 15px 0;
  font-size: 3rem;
  font-weight: 700;
}

.category-emoji {
  font-size: 3.5rem;
  margin-right: 15px;
}

.category-description {
  font-size: 1.2rem;
  margin: 0;
  opacity: 0.9;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.filters-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.category-tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.category-tab {
  border-radius: 20px;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.foods-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 80px; /* 增加底部间距，避免与底部栏太近 */
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #666;
}

.empty-icon {
  font-size: 5rem;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 10px 0;
  font-size: 1.5rem;
  color: #333;
}

.foods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.food-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.food-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.food-image-container {
  position: relative;
  overflow: hidden;
}

.food-image {
  width: 100%;
  height: 200px;
  transition: transform 0.3s ease;
}

.food-card:hover .food-image {
  transform: scale(1.05);
}

.food-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.food-card:hover .food-overlay {
  opacity: 1;
}

.food-info {
  padding: 20px;
}

.food-name {
  margin: 0 0 8px 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.food-description {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.food-meta {
  margin-bottom: 15px;
}

.rating {
  margin-bottom: 8px;
}

.merchant-link {
  color: #667eea;
  text-decoration: none;
  font-size: 0.9rem;
}

.merchant-link:hover {
  text-decoration: underline;
}

.food-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 1.3rem;
  font-weight: 700;
  color: #e74c3c;
}

.currency {
  font-size: 0.9rem;
}

.category-tag {
  background: #f0f2f5;
  color: #666;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 0.8rem;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .page-header h1 {
    font-size: 2rem;
  }
  
  .category-emoji {
    font-size: 2.5rem;
  }
  
  .foods-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
  
  .filters-section {
    padding: 20px;
  }
  
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls .el-input,
  .filter-controls .el-select {
    width: 100% !important;
  }
}
</style> 